/**
 * 
 */
package de.uni_postdam.ling.tcl.util;

import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;

/**
 * @author Christoph Teichmann
 *
 */
public class SynchronizedStringInterner
{

	/**
	 * 
	 */
	private int unused = Integer.MIN_VALUE;
	
	/**
	 * 
	 */
	private final Object2IntOpenHashMap<String> toNum = new Object2IntOpenHashMap<>();
	
	/**
	 * 
	 */
	private final Int2ObjectOpenHashMap<String> fromNum = new Int2ObjectOpenHashMap<>();
	
	/**
	 * 
	 */
	public SynchronizedStringInterner()
	{
		super();
		toNum.defaultReturnValue(Integer.MIN_VALUE);
	}
	
	/**
	 * 
	 * @param number
	 * @return
	 */
	public String revert(int number)
	{
		synchronized(this.fromNum)
		{
			return fromNum.get(number);
		}
	}
	
	/**
	 * 
	 * @param toCode
	 * @return
	 */
	public int get(String toCode)
	{
		synchronized(this.fromNum)
		{
			int code = this.toNum.getInt(toCode);
			if(code == Integer.MIN_VALUE)
			{
				String s = new String(toCode);
				this.toNum.put(toCode, code = ++this.unused);
				this.fromNum.put(code, s);
			}
			return code;
		}
	}
}
